<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-form-item label="uid">
          <el-input size="small" v-model="query.userId" placeholder="uid"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input size="small" v-model="query.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="使用状态">
          <el-select size="small" v-model="query.status" placeholder="请选择" clearable>
            <el-option label="未领取" :value="0"></el-option>
            <el-option label="未使用" :value="1"></el-option>
            <el-option label="已使用" :value="2"></el-option>
            <el-option label="冻结" :value="3"></el-option>
            <el-option label="过期" :value="4"></el-option>
            <el-option label="关闭" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
          </el-button>
          <el-button size="small" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
        </el-form-item>
      </el-form>
      <div class="btn-operate">
        <el-button v-if="permissions.user_redpacket_add" @click="showAddView" type="primary" size="small"
                   icon="el-icon-plus">新增
        </el-button>
      </div>
      <el-table header-row-class-name="container-table-header"
                :data="data" size="small"
                style="width: 100%;margin-bottom: 20px;"
                row-key="redId"
                border stripe
                v-loading="loading">
        <el-table-column prop="userId" label="uid">
        </el-table-column>
        <el-table-column prop="name" label="红包名称">
        </el-table-column>
        <el-table-column prop="amount" label="金额">
        </el-table-column>
        <el-table-column prop="status" label="使用状态">
          <template slot-scope="scope">
            <div>{{ scope.row.status | redPacketStatus }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="expiredTime" label="过期时间">
        </el-table-column>
        <el-table-column prop="minCapital" label="最小起用金额">
        </el-table-column>
        <el-table-column prop="modeType" label="专属红包">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.book_type" :value="scope.row.modeType - 10"/>
          </template>
        </el-table-column>
        <el-table-column prop="usedTime" label="使用时间">
        </el-table-column>
        <el-table-column prop="createTime" label="添加时间">
        </el-table-column>
        <el-table-column
          label="操作" width="170">
          <template slot-scope="scope">
            <el-button v-if="permissions.user_redpacket_add" type="text" size="small" icon="el-icon-edit" @click="showEditBox(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="formTitle" :visible.sync="formBox" :close-on-click-modal="!formBox" :append-to-body="true" :before-close="resetForm">
      <el-form ref="optForm" :model="form" label-width="100px">
        <el-form-item label="客户" prop="userName" :rules="{required: true, message: '客户不能为空', trigger: 'blur'}">
          <el-row>
            <el-col :span="18">
              <el-input v-model="form.userName" maxlength="255" show-word-limit disabled></el-input>
            </el-col>
            <el-col :span="6">
              <el-button @click="showCustomerDialog()">请选择客户</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入名称" :rules="{required: true, message: '名称不能为空', trigger: 'blur'}"></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="form.amount" placeholder="请输入金额"></el-input-number>
        </el-form-item>
        <el-form-item label="最小起用金额" prop="minCapital">
          <el-input-number v-model="form.minCapital" placeholder="请输入最小起用金额"></el-input-number>
        </el-form-item>
        <el-form-item label="过期日期" prop="expiredTime">
          <el-date-picker v-model="form.expiredTime" type="datetime" placeholder="请选择过期日期" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="专属红包" prop="modeType">
          <el-select size="small" v-model="form.modeType" placeholder="请选择" clearable>
            <el-option label="通用" :value="0"></el-option>
            <el-option v-for="dict in dict.type.book_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value) + 10"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态" prop="status" :rules="{required: true, message: '使用状态不能为空', trigger: 'change'}">
          <el-select size="small" v-model="form.status" placeholder="请选择使用状态">
            <el-option label="未领取" :value="0"></el-option>
            <el-option label="未使用" :value="1"></el-option>
            <el-option label="已使用" :value="2"></el-option>
            <el-option label="已冻结" :value="3"></el-option>
            <el-option label="已过期" :value="4"></el-option>
            <el-option label="关闭" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="4" v-model="form.remark" placeholder="请输入备注" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm" size="small" icon="el-icon-close">取消</el-button>
                <el-button type="success" @click="submit" size="small" icon="el-icon-position" :loading="loading">保存</el-button>
            </span>
    </el-dialog>

    <ChoseCustomer :customer-dialog="customerDialog" @setValue="setRelateCustomer" @closeDialog="closeCustomerDialog" />
  </basic-container>
</template>

<script>
import {addObj, fetchList, getObj, putObj} from "@/api/user/redpacket";
import {mapGetters} from "vuex";
import ChoseCustomer from "@/components/exam/ChoseCustomer";

export default {
  components: {
    ChoseCustomer
  },
  dictTypes: ['book_type'],
  data() {
    return {
      importBox: false,
      isEdit: false,
      isView: false,
      viewBox: false,
      formBox: false,
      formTitle: '',
      loading: true,
      query: {},
      form: {},
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      showUploadButton: true,
      fileList: [],
      customerDialog: false,
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permissions"])
  },
  created() {
    this.onLoad(this.page);
  },
  methods: {
    // 获取客户列表
    setRelateCustomer(val) {
      if (val) {
        this.form.userId = val.userId;
        this.form.userName = val.username;
      }
    },
    // 显示客户列表
    showCustomerDialog() {
      this.customerDialog = true
    },
    // 关闭
    closeCustomerDialog(val) {
      this.customerDialog = val
    },
    resetForm() {
      this.formBox = false;
      this.isEdit = false;
      this.isView = false;
      this.form = {};
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.viewBox = false;
      this.fileList = [];
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.current = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      fetchList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.showUploadButton = true
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
      if (this.fileList.length >= 1) {
        this.showUploadButton = false
      }
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    showAddView() {
      this.formTitle = '新增';
      this.formBox = true;
    },
    submit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          if(this.form.redPacketId) {
            putObj(this.form).then(() => {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.resetForm();
              this.onLoad(this.page);
            }, () => {
              this.loading = false;
            });
          } else {
            addObj(this.form).then(() => {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.resetForm();
              this.onLoad(this.page);
            }, () => {
              this.loading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    showEditBox(row) {
      getObj(row.redPacketId).then((res) => {
        this.form = Object.assign({}, res.data.data)
        /*this.$delete(this.form, 'chapterId')
        this.$set(this.form, 'chapterIds', [res.data.data.chapterId])*/
        this.formTitle = '编辑';
        this.formBox = true;
        this.isEdit = true;
      });
    },
  }
};
</script>

<style>
</style>
